package com.superman.dao.impl;

import com.superman.dao.IUserDao;
import com.superman.entity.User;
import com.superman.util.JDBCTemplate;
import com.superman.util.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements IUserDao {

/*
    @Override
    public List<User> queryUser() throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM t_user";
        List<User> users = JDBCTemplate.query(sql, null, new ResultSetHandler<User>(){
            @Override
            public User handleRow(ResultSet rs) throws SQLException {
                return new User(rs.getString("id"), rs.getString("username"), rs.getString("password"),
                        rs.getInt("sex"), rs.getString("id_number"), rs.getString("tel"),
                        rs.getString("addr"));
            }
        });
        return users;
    }
*/

    @Override
    public User singleQueryUser(User user) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM t_user t WHERE t.username = ? AND t.password = ?";
        Object[] params = {user.getUsername(), user.getPassword()};
        User userReturn = JDBCTemplate.singleQuery(sql, params, new ResultSetHandler<User>() {
            @Override
            public User handleRow(ResultSet rs) throws SQLException {
                return new User(rs.getString("id"), rs.getString("username"), rs.getString("password"),
                        rs.getInt("sex"), rs.getString("id_number"), rs.getString("tel"),
                        rs.getString("addr"),rs.getInt("type"));
            }
        });
        return userReturn;
    }

    @Override
    public int insertUser(User user) throws SQLException, ClassNotFoundException {
        String sql = "INSERT INTO t_user t VALUES (?,?,?,?,?,?,?,?)";
        Object[] params = {user.getId(), user.getUsername(), user.getPassword(), Integer.valueOf(user.getSex()),
                user.getId_number(), user.getTel(), user.getAddr(),Integer.valueOf(user.getType())};
        return JDBCTemplate.update(sql, params);
    }
}
